<script setup>
import vis from "vis-network/dist/vis-network.min.js";
import { onMounted, watch } from 'vue';
import PeopleComp from '../Relation/PeopleComp.vue';
import { Plus, Minus, FullScreen, Refresh } from "@element-plus/icons-vue";

var network
const raws = ref([])
let nodes = [{ id: 0, label: User.name, color: '#daa', font: { size: 30 } }], edges = []

// const groups = reactive(['亲戚', '其他人'])
const groups = reactive(['亲戚'])
const options = {
  autoResize: true, //网络将自动检测其容器的大小调整，并相应地重绘自身
  interaction: {
    zoomView: false, //是否能缩放画布
  },
  nodes: {
    shape: 'box', //设置节点node样式为矩形
    fixed: false, //节点node固定可移动
    font: { size: 20, }, //显示字体大小
  },
  edges: {
    arrows: { to: true },
  },
  layout: {
    randomSeed: 5,  // 布局种子，使其每次布局都一样
  },
};
let data

onMounted(() => {
  myPost("/relation/relations", { userToken: User.token },
    (data) => { raws.value = data }
  );
})


// 转化后端的 raws数据，
const handlRaws = () => {
  nodes = [{ id: 0, label: User.name, color: '#daa', font: { size: 30 } }]
  edges = []
  // { createUserName: 'sybit', rGroup: '大学', rId: 55, rName: '刘昊', rNumber: '17311899707' }
  for (const raw of raws.value) {
    nodes.push({ id: raw.rId, label: raw.rName, from: raw.rFromId ?? raw.rGroup, group: raw.rGroup, raw }) // 解析人员节点
    if (raw.rGroup && groups.indexOf(raw.rGroup) == -1) { groups.push(raw.rGroup) } // 归纳组节点
  }
  // 设置组节点
  for (let i = 0; i < groups.length; i++) {
    nodes.push({ id: -i - 1, label: groups[i], color: '#ddd', shape: 'ellipse', font: { size: 20 } })
  }
  // {id: 55, label: '刘昊', from: '大学', raw: {…}}

  for (const node of nodes) {
    if (node.id < 0) { // 先让组和根相连
      edges.push({ from: 0, to: node.id })
    } else if (node.id > 0) {
      if (parseInt(node.from)) {// 别人之后的节点
        edges.push({ from: parseInt(node.from), to: node.id, label: node.raw.rEdgeLabel })
      } else {
        edges.push({ from: -groups.indexOf(node.from) - 1, to: node.id, label: node.raw.rEdgeLabel })
      }
    }
  }
}

watch(raws, (newValue) => {
  handlRaws()
  console.log(raws.value)
  network = new vis.Network(document.getElementById('mynetwork'), { nodes, edges }, options);
  event()
}, { deep: true })

// network生成后需要做的，绑定data、事件
const event = () => {
  data = network.body.data

  network.on('selectNode', (properties) => {
    selectedPeople.value = nodes.find((node) => { return node.id == properties.nodes[0] })
  })
  network.on('deselectNode', () => {
    selectedPeople.value = {}
  })
  network.on('doubleClick', () => {
    if (network.getScale() > 1) {
      setScale(0)
    } else {
      setScale(0.5)
    }
    // console.log(network.getScale())

  })
}

// 添加节点方法
const addNode = (node) => {
  // 人节点 { id: raw.rId, label: raw.rName, from: raw.rFromId ?? raw.rGroup, group: raw.rGroup, raw })
  // 组节点 { id: -i - 1, label: groups[i], color: '#ddd', shape: 'ellipse', font: { size: 20 } })
  // 边 { from: -groups.indexOf(node.from) - 1, to: node.id, label: node.raw.rEdgeLabel })
  // 要同时实现在nodes和network.nodes中同步数据
  let edge
  if (parseInt(node.from)) {// 别人之后的节点
    edge = { from: node.from, to: node.id, label: node.raw.edgeLabel }
  } else {  // 组后的直接节点
    edge = { from: -groups.indexOf(node.from) - 1, to: node.id, label: node.raw.edgeLabel }
  }
  // console.log(node, edge)

  nodes.push(node)
  edges.push(edge)
  data.nodes.add(node)
  data.edges.add(edge)
}
// 修改和添加节点方法，通过直接修改raws，让watch去修改页面
const handleRaws = (r) => {
  // 先查找有没有这个ID
  let i = raws.value.findIndex((raw) => { return r.rId == raw.rId })
  console.log(i)
  if (i >= 0) { // 有就删掉
    raws.value.splice(i, 1)
  } else {// 没有就添加
    raws.value.push(r)
  }
}

// 选中的人的数据
const selectedPeople = ref({})

// 最大化画布
const MaxNetwork = () => {
  let element = document.querySelector('.out-network .network')
  let e = document.querySelector('.out-network')
  if (element.className.indexOf('fixed-network') < 0) {
    element.className += ' fixed-network'
    e.style.backdropFilter = 'none' //会影响fixed-network的全屏效果
  } else {
    e.style.backdropFilter = 'blur(10px)'
    element.className = element.className.substring(0, element.className.indexOf('fixed-network') - 1)
  }
  setTimeout(() => network.fit(), 500)
}
// 缩放按钮
const setScale = (num) => {
  if (num == 0) network.fit()
  if (num < 0 && network.getScale() < 0.12) return
  network.moveTo({ scale: network.getScale() + num });
}

</script>

<template>
  <div>
    <!-- 外层div 用于fixed占位 -->
    <div class="out-network model">
      <div class="network">
        <div id="mynetwork"></div>
        <div class="buttons">
          <el-button type="primary" @click="MaxNetwork()">
            <el-icon>
              <FullScreen />
            </el-icon>
          </el-button>
          <el-button type="primary" @click="setScale(0)">
            <el-icon>
              <Refresh />
            </el-icon>
          </el-button>
          <el-button type="primary" @click="setScale(0.1)">
            <el-icon>
              <Plus />
            </el-icon>
          </el-button>
          <el-button type="primary" @click="setScale(-0.1)">
            <el-icon>
              <Minus />
            </el-icon>
          </el-button>
        </div>
      </div>
    </div>

    <!-- 查看人员表单 -->
    <PeopleComp :selectedPeople="selectedPeople" :groups="groups" :handleRaws="handleRaws" :raws="raws" />

  </div>
</template>

<style scoped lang="less">
.out-network {
  height: 400px;
  padding: 5px;
  // backdrop-filter: none; // 会影响fixed-network的全屏效果

  .network {
    height: 100%;

    #mynetwork {
      height: 100%;
    }

    >.buttons {
      position: absolute;
      right: 20px;
      bottom: 20px;
    }
  }
}




.fixed-network {
  z-index: 51;
  position: fixed;
  background: var(--model-back-color-hover);
  backdrop-filter: blur(5px);

  top: 0px;
  left: 0px;
  height: 100%;
  width: 100%;
}
</style>